package cn.kgc.shiro02;

import cn.kgc.shiro02.realm.CustomerRealm;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

import java.util.Arrays;
import java.util.List;

public class App {

    public static void main(String[] args) {

        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        //defaultSecurityManager.setRealm(new IniRealm("classpath:user.ini"));
        CustomerRealm realm = new CustomerRealm();


        //数据库中的密码进行了加密处理 需要重新设置密码凭证匹配器
        // 创建凭证匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        //设置密码散列的次数
        hashedCredentialsMatcher.setHashIterations(20);
        realm.setCredentialsMatcher(hashedCredentialsMatcher);

        defaultSecurityManager.setRealm(realm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        //认证主体
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("tom", "123456");
        // 没有异常则认证通过
        try {

            subject.login(usernamePasswordToken);
            System.out.println("=======认证通过=========");

            //  用户授权操作  编程式权限控制
            boolean admin = subject.hasRole("admin");

            //if(subject.hasRole("admin")){
            //    userService.add();
            //}
            System.out.println(" has role admin = " + admin);
            //判定用户是否同时拥有某些角色
            List<String> roles = Arrays.asList("admin", "super");
            boolean b = subject.hasAllRoles(roles);
            System.out.println("b = " + b);

            roles = Arrays.asList("admin", "user");
            boolean[] booleans = subject.hasRoles(roles);
            for (boolean aBoolean : booleans) {
                System.out.println("aBoolean = " + aBoolean);
            }

            //基于权限字符串进行权限判定
            boolean permitted = subject.isPermitted("user:add");
            System.out.println("permitted = " + permitted);

            permitted = subject.isPermitted("user:update");
            System.out.println("permitted = " + permitted);



        } catch (IncorrectCredentialsException e) {
            e.printStackTrace();
            System.out.println("==========密码异常========");
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("===========用户名错误============");
        }

    }
}
